package tech.jitao.aly_oss;

import android.os.Environment;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.shaohui.advancedluban.Luban;

/**
 * @author longdw
 * 2020/10/15 12:51 PM
 * www.longdw.com
 */
public class CompressUtil {
    public static void compressFile(String filePath, final CompressCallback callback,String tempPath) {
//        context.getCacheDir().getPath()
        File file = new File(filePath);
        System.out.println("exist----->" + file.exists());
        Luban.compress(new File(filePath), new File(getPath(tempPath)))
                .setMaxSize(600)
                .putGear(Luban.THIRD_GEAR)
                .asObservable().subscribe(new Observer<File>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(File file) {
//               byte[] data = fileConvertToByteArray(file);
                callback.onCompress(file);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {}
        });
    }

    private static byte[] fileConvertToByteArray(File file) {
        byte[] data = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            data = baos.toByteArray();

            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }


    private static String getPath(String tempPath) {
        String path = tempPath;
        File file = new File(path);
        file.mkdirs();
        return path;
    }

    private static String getRootFilePath() {
        String path;
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/";
        initFilePath(path);
        return path;
    }

    private static boolean initFilePath(String path) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                return file.mkdirs();
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public interface CompressCallback {
        void onCompress(File file);
    }
}
